<template>
  <div class="login">
    <div class="login-con">

      <!-- 表单部分 -->
      <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="login-box">
        <!-- 顶部切换 -->
        <h3 class="login-title">{{ model == 'login' ? '欢迎登陆' : '用户注册' }}</h3>
        <!-- 修改提示文字 并且修改type类型 与v-model绑定的数据 并且添加类名-->
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input type="text" placeholder="请输入用户名" v-model.trim="ruleForm.username"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email" class="item-from" v-if="model != 'login'">
          <el-input v-model="ruleForm.email" type="text" placeholder="请输入邮箱" autocomplete="off" />
        </el-form-item>
        <!-- 密码框 -->
        <el-form-item label="密码" prop="password" class="item-from">
          <el-input id="password" placeholder="请输入密码" v-model="ruleForm.password" type="password" autocomplete="off"
            minlength="6" maxlength="20" />
        </el-form-item>
        <!-- 确认密码 -->
        <el-form-item prop="passwords" class="item-from" v-show="model === 'register'" label="重复密码">
          <el-input placeholder="请确认密码" type="password" v-model="ruleForm.passwords" autocomplete="off" minlength="6"
            maxlength="20"></el-input>
        </el-form-item>
        <!-- 按钮设置 -->
        <el-form-item label-width="20px">
          <el-button type="primary" @click="submitForm(ruleFormRef)" style="margin-left: 90px">{{ model == 'login'
            ? '登陆' : '注册'
          }}
          </el-button>
          <el-button @click="resetForm(ruleFormRef)" style="margin-left: 50px">重置</el-button>
          <el-button @click.prevent="changeModel" style="margin-left: 50px">{{ model == 'login' ? '注册' : '登陆'
          }}</el-button>
        </el-form-item>
      </el-form>
      <!-- 表单部分 -->
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance, ElMessage } from "element-plus";
import http from '../../api/api'
import useMd5 from '../../hooks/useMd5'

import { useRouter } from 'vue-router'

const router = useRouter()
const model = ref("login");
/**
 * 声明函数
 */
const ruleFormRef = ref<FormInstance>();
// 检查用户名输入不能为空
const checkUser = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error("用户名不能为空"));
  } else {
    callback();
  }
}
// 邮箱用户名验证
const checkEmail = (rule: any, value: any, callback: any) => {
  // 创建邮箱正则来进行邮箱格式校验
  let reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
  if (value === '') {
    callback(new Error("邮箱不能为空！"));
  } else if (!reg.test(value)) {
    return callback(new Error("邮箱格式有误！"));
  } else {
    callback();
  }
};
// 设置密码验证
const validatePass = (rule: any, value: any, callback: any) => {
  let reg = /^[0-9]{6,15}$/;// 验证密码 6至15位的字母+数字 
  if (value === "") {
    callback(new Error("密码不能为空"));
  } else if (!reg.test(value)) {
    callback(new Error("密码格式有误!6至15位的字母+数字"));
  } else {
    callback();
  }
};
// 重复密码验证
const validatePass2 = (rule: any, value: any, callback: any) => {
  // 因为登录没有重复密码 所以在登录的时候跳过
  if (model.value === 'login') { callback(); }
  if (value === "") {
    callback(new Error("重复密码不能为空"));
  } else if (value !== ruleForm.password) {
    callback(new Error("两次密码必须相同"));
  } else {
    callback();
  }
};
// 表单内容
const ruleForm = reactive({
  username: "",
  email: "",
  password: "",
  passwords: "",
});
const rules = reactive({
  username: [{ validator: checkUser, trigger: 'blur' }],
  password: [{ validator: validatePass, trigger: "blur" }],
  passwords: [{ validator: validatePass2, trigger: "blur" }],
  email: [{ validator: checkEmail, trigger: "blur" }],
});
// 提交按钮
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (!valid) {
      console.log('输入不允许为空');

      return false;
    } else if (model.value === 'login') {
      console.log("login!");
      //发送请求
      http(`/register?username=${ruleForm.username}&password=${useMd5(ruleForm.password).value}`).then((res) => {
        console.log(res, 666);
        let { data } = res
        if (data.length != 0) {
          ElMessage({
            message: '登陆成功！',
            type: 'success',
          })
          resetForm(ruleFormRef.value)

          let obj = {
            id: data[0].id,
            username: data[0].username,
            power: data[0].power
          }
          localStorage.setItem('user', JSON.stringify(obj))
          router.push('/echarts')
          console.log(JSON.stringify(obj),'333333333');
          
        } else {
          ElMessage({
            message: '用户名或密码错误！',
            type: 'error',
          })
        }
      })
    } else if (model.value === 'register') {
      //注册
      let data = {
        "username": ruleForm.username,
        "password": useMd5(ruleForm.password).value,
        "email": ruleForm.email,
        "power": []
      }
      http('/register', "POST", data).then((res) => {
        console.log(res.status);
        let { data } = res
        if (Object.keys(data).length != 0) {
          ElMessage({
            message: '注册成功！',
            type: 'success',
          })
          changeModel()
        } else {
          ElMessage({
            message: '注册失败！',
            type: 'error',
          })
        }
      })
    }
    else {
      console.log("error submit!");
      return false;
    }
  });
};
// 重置按钮
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

//切换注册登陆
const changeModel = () => {
  model.value = model.value == 'login' ? 'register' : 'login'
  resetForm(ruleFormRef.value)
}
</script>

<style lang="scss" scoped>
.login {
  height: 100vh; //100%的窗口高度
  overflow: hidden;

  .login-title {
    text-align: center;
    margin-bottom: 20px;
    font-size: 20px;
  }

  .login-box {
    width: 400px;
    margin: 120px auto;
    border: 1px solid #dcdfe6;
    padding: 30px 55px 10px 20px;
    border-radius: 5px;
    box-shadow: 0 0 30px #dcdfe6;

    .el-button--info {
      margin-left: 60px;
    }
  }
}

.el-form-item {
  margin-bottom: 18px;
}

// .el-form-item__content{
//     margin-left: 0 !important;
// }
</style>